package utils

import (
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"golang.org/x/crypto/bcrypt"
	"math/rand"
	"time"
)

const fixedStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" // 固定字符串

// BcryptHash 使用 bcrypt 对密码进行加密
func BcryptHash(password string) string {
	bytes, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(bytes)
}

// BcryptCheck 对比明文密码和数据库的哈希值
func BcryptCheck(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}

// EncryptionSha256 密码加密
func EncryptionSha256(password, salt string) string {
	str := fmt.Sprintf("%s%s", password, salt)
	return base64.RawURLEncoding.EncodeToString(sha256.New().Sum([]byte(str)))
}

func RandString(count int) string {
	rand.Seed(time.Now().UnixNano()) // 使用当前时间作为随机数种子
	var result string                // 存储结果的字符串
	for i := 0; i < count; i++ {
		result += string(fixedStr[rand.Intn(len(fixedStr))]) // 从固定字符串中随机选择一个字符
	}
	return result
}
